//
//  Created by Rene Dohan on 11/22/11.
//


#import "TransactionData.h"
#import "PapRequest.h"
#import "Lang.h"
#import "TransactionRequest.h"
#import "LoadRowRequest.h"

@implementation TransactionData {
    NSString *fromTime;
    NSMutableDictionary *transactionRequests;
    NSMutableDictionary *loadRowRequests;
    Boolean *allCountFired;
}
@synthesize listener;

- (id)init {
    loadRowRequests = [NSMutableDictionary new];
    return [super init];
}

- (TransactionRequest *)getRequestFor :(NSInteger)index {
    NSInteger requestIndex = index / 30;
    TransactionRequest *request = [transactionRequests objectForKey:[Lang asStringInt:requestIndex]];
    if (!request) {
        request = [TransactionRequest new];
        request.transactionsListener = listener;
        request.action = @"load_transactions";
        request.index = requestIndex;
        if (fromTime) {
            [request addArgument:@"fromtime" :fromTime];
        }
        [transactionRequests setObject:request forKey:[Lang asStringInt:requestIndex]];
        [request send];
    }
    return request;
}

- (void)reset {
    transactionRequests = [NSMutableDictionary new];
    allCountFired = false;
    [transactionRequests removeAllObjects];
    fromTime = nil;
    TransactionRequest *request = [self getRequestFor:0];
    request.listener = self;
}

- (void)loadRow:(NSInteger)rowIndex :(UITableViewCell *)cell {
    NSString *cellKey = [Lang asStringInt:cell.hash];

    LoadRowRequest *previousRequest = [loadRowRequests objectForKey:cellKey];
    if (previousRequest) previousRequest.valid = false;

    LoadRowRequest *loadRowRequest = [LoadRowRequest new];
    loadRowRequest.rowIndex = rowIndex;
    loadRowRequest.cell = cell;
    loadRowRequest.valid = true;

    [loadRowRequests setObject:loadRowRequest forKey:cellKey];

    TransactionRequest *request = [self getRequestFor:rowIndex];
    [request addLoadRowRequest:loadRowRequest];
}

- (void)onRequestLoaded:(PapRequest *)request {
    NSString *allCount = [request.data objectForKey:@"all_count"];
    fromTime = [request.data objectForKey:@"fromtime"];
    [listener onDataCount:[allCount intValue]];
}

- (void)onRequestFailed:(PapRequest *)request {
}


@end